<?php

namespace App\Admin\Actions\NewsAction;

use App\Models\User;
use Illuminate\Support\Facades\DB;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use OpenAI;

class NewsTranslate extends RowAction
{
    public $name = '新闻翻译';
    
    public function handle(Model $model)
    {
	    /**
	     * @var $model User
	     */
    	

	    $yourApiKey = getenv('CHATGPT_API_KEY');
	   
		//$client = OpenAI::client($yourApiKey);

		$data = [];

		if($model->title_cn){

			$titleContent = [
			    'model' => 'gpt-3.5-turbo',
			    'messages' => [
			    	['role' => 'system', "content"=> "你是个翻译工作者"],
			        ['role' => 'user', 'content' => '将标题【'.$model->title_cn.'】翻译成英文'],
			    ],
			]; 

			$titleResult = $this->curl($titleContent);
			
			$titleResult = json_decode($titleResult,true);

			$data['title_zn'] = $titleResult['choices'][0]['message']['content']; 
		}


		if($model->content_cn){

			$strlen = strlen($model->content_cn);

			if($strlen < 5000) {
				//dd(321);
				$content = [
				    'model' => 'gpt-3.5-turbo',
				    'messages' => [
				    	['role' => 'system', "content"=> "你是个翻译工作者"],
				        ['role' => 'user', 'content' => '将内容【'.$model->content_cn.'】翻译成英文'], 
				        ['role' => 'user', 'content' => '保留html标签']
				    ]
				];
				$content = $this->curl($content);
			
				$content = json_decode($content,true);

				$data['content_zn'] = $content['choices'][0]['message']['content']; 
			}else{

				$pattern = "/<p.*?>(.*?)<\/p>/is"; // 正则表达式，用于匹配P标签及其内容
				 
				// 使用preg_split进行拆分
				$parts = preg_split($pattern, $model->content_cn, -1, PREG_SPLIT_DELIM_CAPTURE);
				
				$res = [];
				$i = 0;
				foreach($parts as $k=>$v){
					if($k == 0){
						$res[$i] = $v;

					}else{

						if(strlen($res[$i]) < 5000){
							$res[$i] = $res[$i]."<p>".$v."</p>";

						}else{
							$i++;
							$res[$i] = "<p>".$v."</p>";

						}


					}
				
				}

				$data['content_zn'] = "";

				foreach($res as $k=>$v){
					$content = [
					    'model' => 'gpt-3.5-turbo',
					    'messages' => [
					    	['role' => 'system', "content"=> "你是个翻译工作者"],
					        ['role' => 'user', 'content' => '将内容【'.$v.'】翻译成英文,保留html标签'],
					    ]
					];
					$content = $this->curl($content);
			
					$content = json_decode($content,true);

					$data['content_zn'] .= $content['choices'][0]['message']['content']; 

				}

			}
			


			//$data['content_zn'] = $content->choices[0]->message->content; 
		}


		if($model->brief){


			$briefContent = [
			    'model' => 'gpt-3.5-turbo',
			    'messages' => [
			    	['role' => 'system', "content"=> "你是个翻译工作者"],
			        ['role' => 'user', 'content' => '将内容【'.$model->brief.'】翻译成英文'],
			    ],
			];

			$briefContent = $this->curl($briefContent);
			
			$briefContent = json_decode($briefContent,true);

			$data['brief_zn'] =  $briefContent['choices'][0]['message']['content']; 
		}
    	

		 $model->update($data);
	  
    	
    	
	    return $this->response()->success('新闻翻译完成')->refresh();
    }

    public function curl($data){

		$curl = curl_init();
		$data = json_encode($data);


		curl_setopt_array($curl, array(
		   CURLOPT_URL => 'https://api.chatanywhere.com.cn/v1/chat/completions',
		   CURLOPT_RETURNTRANSFER => true,
		   CURLOPT_ENCODING => '',
		   CURLOPT_MAXREDIRS => 10,
		   CURLOPT_TIMEOUT => 0,
		   CURLOPT_FOLLOWLOCATION => true,
		   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		   CURLOPT_CUSTOMREQUEST => 'POST',
		   CURLOPT_POSTFIELDS =>$data,
		   CURLOPT_HTTPHEADER => array(
		      'Authorization: Bearer '.env('CHATGPT_API_KEY'),
		      'User-Agent: Apifox/1.0.0 (https://apifox.com)',
		      'Content-Type: application/json'
		   ),
		));

	   $response = curl_exec($curl);

	   //dd($response);
	   return $response;
	}
	
	public function dialog()
	{
		$this->confirm('确定翻译该新闻吗?');
	}
}
